package com.hec.yygh.sms.service.impl;

import com.hec.yygh.sms.service.SmsService;
import com.hec.yygh.sms.utils.HttpUtils;
import com.hec.yygh.sms.utils.RandomUtil;
import com.hec.yygh.vo.msm.MsmVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Boolean send(String phone) {

        String s = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(s)){
            return true;
        }

        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        String appcode = "b6d556d94a8a4d7787fe59858ec4b51d";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        String code = RandomUtil.getFourBitRandom();
        querys.put("param", "code:"+code);
        querys.put("tpl_id", "TP1711063");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            redisTemplate.opsForValue().set(phone,code,3, TimeUnit.HOURS);
            System.out.println(response.toString());
            return true;
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void sendInfo(MsmVo msmVo) {
        String phone = msmVo.getPhone();
        String templateCode = msmVo.getTemplateCode();
        System.out.println("就诊人预约挂号成功短信提示...");
    }
}
